package com.jolink.omiis.wechat.message;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jolink.omiis.wechat.message.type.UserType;

/**
 * 
 * 消息处理器Factory
 * 
 * @author WangYanqing
 *
 */
public class MessageHandlerFactory {

	private static Logger logger = LoggerFactory.getLogger(MessageHandlerFactory.class);
	@SuppressWarnings({ "unchecked", "rawtypes" })
	private static Map<String, Class<? extends AbstractMessageHandler>> messageHandlers = new ConcurrentHashMap();

	private MessageHandlerFactory() {
	}

	@SuppressWarnings("unchecked")
	public static <T> T createMessageHandler(String userType) {
		T t = null;
		try {
			t = (T) messageHandlers.get(userType).newInstance();
		} catch (InstantiationException | IllegalAccessException e) {
			logger.error(e.getMessage(), e);
		}
		return t;
	}

	private static void registerMessageHandlers() {
		logger.info("开始加载MessageHandler......");
		messageHandlers.put(UserType.AppId.getValue(), AuthorityMessageHandler.class);
		messageHandlers.put(UserType.ToUserName.getValue(), DefaultMessageHandler.class);
		messageHandlers.put(UserType.Broker.getValue(), BrokerMessageHandler.class);
		logger.info("加载MessageHandler完成。");
	}

	private static MessageHandlerFactory instance = null;

	public static MessageHandlerFactory getInstance() {
		if (instance == null) {
			synchronized (MessageHandlerFactory.class) {
				if (instance == null) {
					instance = new MessageHandlerFactory();
					registerMessageHandlers();
				}
			}
		}
		return instance;
	}
}
